package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    @PostMapping
    public R<String> add(@RequestBody Category category){
        log.info("添加数据：{}",category);
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){

        //构造分页器
        Page page1 = new Page<>(page, pageSize);
        //编写条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件

        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(page1,lambdaQueryWrapper);
        return R.success(page1);
    }

    @DeleteMapping
    public R<String> deleteById(Long id){
        categoryService.remove(id);
        return R.success("删除成功了");
    }


    @PutMapping
    public R<String> updateById(@RequestBody Category category){
        log.info("修改分类信息：{}",category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R<List<Category>> listR(Category category){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加条件查询
        wrapper.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    /*@GetMapping("/list")
    public R<List<Dish>> listR(Category category){
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加条件查询
        wrapper.eq(Dish::getId,category.getId());
        //添加排序条件
        wrapper.orderByDesc(Dish::getUpdateTime).orderByAsc(Dish::getSort);
        List<Dish> list = dishService.list(wrapper);
        return R.success(list);*/
    }
}
